<?php

class AdminPageController extends \BaseController {
    
    use HandleImagesTrait; // traits para addImagesToEntidad()

	/**
	 * Display a listing of the resource.
	 * GET /pages
	 *
	 * @return Response
	 */
    public function index() {
        $pages = Page::orderBy('position')->get();
        return View::make('admin.pages.index', ['pages' => $pages]);
    }

	/**
	 * Show the form for editing the specified resource.
	 * GET /pages/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
    public function edit($id) {
        $page = Page::find($id);
        $images = $page->imagesOrdered;
        $entidad = 'page';
        return View::make('admin.pages.edit', ['page' => $page, 'images' => $images, 'entidad' => $entidad]);
    }

	/**
	 * Update the specified resource in storage.
	 * PUT /pages/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
    public function update($id) {
        $validatorPage = Page::validate(Input::all());
        
        // validate imagenes
        foreach (Input::file('files') as $file) {
            $validatorImg = Imageapa::validate(['file' => $file]);
            if ($validatorImg->fails()) {
                return Redirect::back()->withErrors($validatorImg)->withInput();
            }
        }
        if ($validatorPage->fails()) {
            return Redirect::back()->withErrors($validatorPage)->withInput();
        } 
        else {
            // store
            $titulo = Input::get('titulo');
            $slug = Str::slug($titulo, $separator = '-');
            
            $page = Page::find($id);
            $page->titulo = $titulo;
            $page->slug = $slug;
            $page->texto = Input::get('texto');
            $page->estado = Input::get('estado');
            
            $page->save();

            //Image managing
            if(Input::hasFile('files')){
                $this->addImagesToEntidad(Input::file('files'), $page, 'page_id', 'imageapa_page', 'Imageapa');
            }

            // redirect
            Session::flash('message', 'Modificación exitosa.');
            return Redirect::to('admin/pages');
        }
    }

}